import { getPexelsListApi } from "@/apis/index.js";
import { PexelsItem, PexelsQuery } from "@/types/index.js";
import { defineStore } from "pinia";
import { ref } from "vue";
import { PEXELS_PAGE_SIZE } from "./pexels.js";


export const useSearchPexelsStore = defineStore('search_pexels', () => {
  const list = ref<PexelsItem[]>([]);
  const isLoading = ref<boolean>(false);
  const isFinished = ref<boolean>(false);
  const page = ref<number>(1);
  const currentQuery = ref<string>('');

  const itemDetail = ref<PexelsItem | null>(null);


  const loadMore = async (q: string) => {
    if (q !== currentQuery.value) {
      resetState();
      currentQuery.value = q;
    }
    try {
      if (isLoading.value || isFinished.value) {
        return;
      }
      isLoading.value = true;
      const query: PexelsQuery = {
        categoryId: '',
        searchText: q,
        page: page.value,
        size: PEXELS_PAGE_SIZE
      };
      const res = await getPexelsListApi(query);
      list.value.push(...res.list);
      page.value++;
      if (list.value.length >= res.total) {
        isFinished.value = true
      }
    } catch (error) {
      console.error("Failed load more:", error);
    } finally {
      isLoading.value = false;
    }
  }


  const setItemDeatil = (item: PexelsItem) => {
    itemDetail.value = item
  }


  const resetState = () => {
    list.value = [];
    isLoading.value = false;
    isFinished.value = false;
    page.value = 1;
    currentQuery.value = '';
  }

  return {
    list,
    isLoading,
    isFinished,
    page,
    loadMore,
    resetState,
    currentQuery,
    itemDetail,
    setItemDeatil
  }
})